//
//  SellViewController.swift
//  二次源
//
//  Created by 李建文 on 2016/12/12.
//  Copyright © 2016年 二次源. All rights reserved.
//

import UIKit

class SellViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {

    @IBOutlet weak var showView: UIView!
    
    var net:Net = Net()
    
    var itemName:[String] = []
    var itemPhone:[String] = []

    
    //屏幕的宽和高
    let width = UIScreen.main.bounds.width
    let height = UIScreen.main.bounds.height
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        sendRequest()
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func sendRequest(){
        let net:Net = Net()
        net.addUrl(url: "/superSell")
        //self.net.addParames(key: "uid", value: "2")
        net.sendPostWithParam()
        //延时1秒执行
        let time: TimeInterval = 1.0
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time) {
            let data:JSON = net.getData()
            let a = data[0]["count"][0]["count(sellid)"].description
            let b:Int = Int(a)!
            for i:Int in 0 ..< b {
                let message = data[0]["sellInfoname"]
                let address = message[i]["name"]
                self.itemName.append(address.description)
                let message2 = data[0]["sellInfophone"]
                let address2 = message2[i]["phone"]
                self.itemPhone.append(address2.description)
            }
            print(self.itemName)
            print(self.itemPhone)
            //加载UICollectionView
            self.loadCollectionView()
        }

    }
    
    func loadCollectionView(){
        //定义collectionView的布局类型,流布局
        let layout = UICollectionViewFlowLayout()
        //设置cell的大小
        layout.itemSize = CGSize(width: width/2, height: height/4)
        //滑动方向，选择垂直方向
        layout.scrollDirection = .vertical
        //每个item之间最小的距离
        layout.minimumInteritemSpacing = 2
        //每行之间的最小间距
        layout.minimumLineSpacing = 0
        //定义一个collectionView
        let collectionView = UICollectionView(frame: CGRect(x: 5, y:height*0.1, width:width-10, height: height - 100), collectionViewLayout: layout)
        //设置collectionView的背景颜色
        collectionView.backgroundColor = UIColor.white
        
        //设置collectionView的代理和数据源
        collectionView.delegate = self
        collectionView.dataSource = self
        
        //注册collectionViewCell的注册
        collectionView.register(UINib(nibName: "sellCollectionViewCell",bundle: nil), forCellWithReuseIdentifier: "sellCell")
        
        //header的注册
        collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader,
                                     withReuseIdentifier: "headView")
        self.view.addSubview(collectionView)
    }
    
    //collectionView中的section数量
    private func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }
    
    //设置每个section中有多少个
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return itemName.count
    }
    
    //绘制collectionView的Cell
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "sellCell", for: indexPath as IndexPath) as! sellCollectionViewCell
        cell.imageView.image = UIImage(named: "sell\(indexPath.row)")
        cell.name.text = itemName[indexPath.row]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let headView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headView", for: indexPath as IndexPath)
        headView.backgroundColor = UIColor.white
        return headView
    }
    
    // #MARK: --UICollectionViewDelegate的代理方法
    /**
     Description:当点击某个Item之后的回应
     */
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("(\(indexPath.section),\(indexPath.row))")
        let alertController = UIAlertController(title: "系统提示",
                                                message: "如果您要购买的话请联系："+itemPhone[indexPath.row], preferredStyle: .alert)
        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        let okAction = UIAlertAction(title: "好的", style: .default, handler: {
            action in
            print("点击了确定")
        })
        alertController.addAction(cancelAction)
        alertController.addAction(okAction)
        self.present(alertController, animated: true, completion: nil)

    }
    
    //#MARK: --UICollectionViewDelegateFlowLayout的代理方法
    /**
     - returns: header的大小
     */
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width: width, height: 0)
    }
    /**
     Description:可以定制不同的item
     
     - returns: item的大小
     */
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if  indexPath.row % 2 == 1{
            return CGSize(width: width/2.1, height: height/3.2)
        }
        else{
            return CGSize(width: width/2.1, height: height/3.2)
        }
        
    }
    
    @IBAction func didBack(_ sender: AnyObject) {
        self.dismiss(animated: true, completion: nil)
        
    }
    

    
}
